home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Objects / object.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  14KB  |  636 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Generic object operations; and implementation of None (NoObject) */
  33.  
  34. #include "allobjects.h"
  35.  
  36. #include "protos/object_protos.h"
  37.  
  38. #if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
  39. long ref_total;
  40. #endif
  41.  
  42. /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
  43.    These are used by the individual routines for object creation.
  44.    Do not call them otherwise, they do not initialize the object! */
  45.  
  46. #ifdef COUNT_ALLOCS
  47. static typeobject *type_list;
  48. extern int tuple_zero_allocs, fast_tuple_allocs;
  49. extern int quick_int_allocs, quick_neg_int_allocs;
  50. extern int null_strings, one_strings;
  51. void
  52. dump_counts()
  53. {
  54.     typeobject *tp;
  55.  
  56.     for (tp = type_list; tp; tp = tp->tp_next)
  57.         fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
  58.             tp->tp_name, tp->tp_alloc, tp->tp_free,
  59.             tp->tp_maxalloc);
  60.     fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
  61.         fast_tuple_allocs, tuple_zero_allocs);
  62.     fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
  63.         quick_int_allocs, quick_neg_int_allocs);
  64.     fprintf(stderr, "null strings: %d, 1-strings: %d\n",
  65.         null_strings, one_strings);
  66. }
  67.  
  68. PyObject *
  69. get_counts()
  70. {
  71.     PyTypeObject *tp;
  72.     PyObject *result;
  73.     PyObject *v;
  74.  
  75.     result = PyList_New(0);
  76.     if (result == NULL)
  77.         return NULL;
  78.     for (tp = type_list; tp; tp = tp->tp_next) {
  79.         v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_alloc,
  80.                   tp->tp_free, tp->tp_maxalloc);
  81.         if (v == NULL) {
  82.             Py_DECREF(result);
  83.             return NULL;
  84.         }
  85.         if (PyList_Append(result, v) < 0) {
  86.             Py_DECREF(v);
  87.             Py_DECREF(result);
  88.             return NULL;
  89.         }
  90.         Py_DECREF(v);
  91.     }
  92.     return result;
  93. }
  94.  
  95. void
  96. inc_count(tp)
  97.     typeobject *tp;
  98. {
  99.     if (tp->tp_alloc == 0) {
  100.         /* first time; insert in linked list */
  101.         if (tp->tp_next != NULL) /* sanity check */
  102.             fatal("XXX inc_count sanity check");
  103.         tp->tp_next = type_list;
  104.         type_list = tp;
  105.     }
  106.     tp->tp_alloc++;
  107.     if (tp->tp_alloc - tp->tp_free > tp->tp_maxalloc)
  108.         tp->tp_maxalloc = tp->tp_alloc - tp->tp_free;
  109. }
  110. #endif
  111.  
  112. #ifndef MS_COREDLL
  113. object *
  114. newobject(tp)
  115.     typeobject *tp;
  116. #else
  117. object *
  118. newobject(tp,op)
  119.     typeobject *tp;
  120.     PyObject *op;
  121. #endif
  122. {
  123. #ifndef MS_COREDLL
  124.     object *op = (object *) malloc(tp->tp_basicsize);
  125. #endif
  126.     if (op == NULL)
  127.         return err_nomem();
  128.     op->ob_type = tp;
  129.     NEWREF(op);
  130.     return op;
  131. }
  132.  
  133. #ifndef MS_COREDLL
  134. varobject *
  135. newvarobject(tp, size)
  136.     typeobject *tp;
  137.     int size;
  138. #else
  139. varobject *
  140. newvarobject(tp, size, op)
  141.     typeobject *tp;
  142.     int size;
  143.     varobject *op;
  144. #endif
  145. {
  146. #ifndef MS_COREDLL
  147.     varobject *op = (varobject *)
  148.         malloc(tp->tp_basicsize + size * tp->tp_itemsize);
  149. #endif
  150.     if (op == NULL)
  151.         return (varobject *)err_nomem();
  152.     op->ob_type = tp;
  153.     op->ob_size = size;
  154.     NEWREF(op);
  155.     return op;
  156. }
  157.  
  158. int
  159. printobject(op, fp, flags)
  160.     object *op;
  161.     FILE *fp;
  162.     int flags;
  163. {
  164.     int ret = 0;
  165.     if (sigcheck())
  166.         return -1;
  167.     if (op == NULL) {
  168.         fprintf(fp, "<nil>");
  169.     }
  170.     else {
  171.         if (op->ob_refcnt <= 0)
  172.             fprintf(fp, "<refcnt %u at %lx>",
  173.                 op->ob_refcnt, (long)op);
  174.         else if (op->ob_type->tp_print == NULL) {
  175.             if (op->ob_type->tp_repr == NULL) {
  176.                 fprintf(fp, "<%s object at %lx>",
  177.                     op->ob_type->tp_name, (long)op);
  178.             }
  179.             else {
  180.                 object *s;
  181.                 if (flags & PRINT_RAW)
  182.                     s = strobject(op);
  183.                 else
  184.                     s = reprobject(op);
  185.                 if (s == NULL)
  186.                     ret = -1;
  187.                 else if (!is_stringobject(s)) {
  188.                     err_setstr(TypeError,
  189.                            "repr not string");
  190.                     ret = -1;
  191.                 }
  192.                 else {
  193.                     fprintf(fp, "%s", getstringvalue(s));
  194.                 }
  195.                 XDECREF(s);
  196.             }
  197.         }
  198.         else
  199.             ret = (*op->ob_type->tp_print)(op, fp, flags);
  200.     }
  201.     if (ret == 0) {
  202.         if (ferror(fp)) {
  203.             err_errno(IOError);
  204.             clearerr(fp);
  205.             ret = -1;
  206.         }
  207.     }
  208.     return ret;
  209. }
  210.  
  211. object *
  212. reprobject(v)
  213.     object *v;
  214. {
  215.     if (sigcheck())
  216.         return NULL;
  217.     if (v == NULL)
  218.         return newstringobject("<NULL>");
  219.     else if (v->ob_type->tp_repr == NULL) {
  220.         char buf[120];
  221.         sprintf(buf, "<%.80s object at %lx>",
  222.             v->ob_type->tp_name, (long)v);
  223.         return newstringobject(buf);
  224.     }
  225.     else
  226.         return (*v->ob_type->tp_repr)(v);
  227. }
  228.  
  229. object *
  230. strobject(v)
  231.     object *v;
  232. {
  233.     if (v == NULL)
  234.         return newstringobject("<NULL>");
  235.     else if (is_stringobject(v)) {
  236.         INCREF(v);
  237.         return v;
  238.     }
  239.     else if (v->ob_type->tp_str != NULL)
  240.         return (*v->ob_type->tp_str)(v);
  241.     else {
  242.         object *func;
  243.         object *res;
  244.         if (!is_instanceobject(v) ||
  245.             (func = getattr(v, "__str__")) == NULL) {
  246.             err_clear();
  247.             return reprobject(v);
  248.         }
  249.         res = call_object(func, (object *)NULL);
  250.         DECREF(func);
  251.         return res;
  252.     }
  253. }
  254.  
  255. static object *
  256. do_cmp(v, w)
  257.     object *v, *w;
  258. {
  259.     /* __rcmp__ actually won't be called unless __cmp__ isn't defined,
  260.        because the check in cmpobject() reverses the objects first.
  261.        This is intentional -- it makes no sense to define cmp(x,y) different
  262.        than -cmp(y,x). */
  263.     if (is_instanceobject(v) || is_instanceobject(w))
  264.         return instancebinop(v, w, "__cmp__", "__rcmp__", do_cmp);
  265.     return newintobject((long)cmpobject(v, w));
  266. }
  267.  
  268. int
  269. cmpobject(v, w)
  270.     object *v, *w;
  271. {
  272.     typeobject *tp;
  273.     if (v == w)
  274.         return 0;
  275.     if (v == NULL)
  276.         return -1;
  277.     if (w == NULL)
  278.         return 1;
  279.     if (is_instanceobject(v) || is_instanceobject(w)) {
  280.         object *res;
  281.         int c;
  282.         if (!is_instanceobject(v))
  283.             return -cmpobject(w, v);
  284.         res = do_cmp(v, w);
  285.         if (res == NULL) {
  286.             err_clear();
  287.             return (v < w) ? -1 : 1;
  288.         }
  289.         if (!is_intobject(res)) {
  290.             DECREF(res);
  291.             return (v < w) ? -1 : 1;
  292.         }
  293.         c = getintvalue(res);
  294.         DECREF(res);
  295.         return (c < 0) ? -1 : (c > 0) ? 1 : 0;    
  296.     }
  297.     if ((tp = v->ob_type) != w->ob_type) {
  298.         if (tp->tp_as_number != NULL &&
  299.                 w->ob_type->tp_as_number != NULL) {
  300.             if (coerce(&v, &w) != 0) {
  301.                 err_clear();
  302.                 /* XXX Should report the error,
  303.                    XXX but the interface isn't there... */
  304.             }
  305.             else {
  306.                 int cmp = (*v->ob_type->tp_compare)(v, w);
  307.                 DECREF(v);
  308.                 DECREF(w);
  309.                 return cmp;
  310.             }
  311.         }
  312.         return strcmp(tp->tp_name, w->ob_type->tp_name);
  313.     }
  314.     if (tp->tp_compare == NULL)
  315.         return (v < w) ? -1 : 1;
  316.     return (*tp->tp_compare)(v, w);
  317. }
  318.  
  319. long
  320. hashobject(v)
  321.     object *v;
  322. {
  323.     typeobject *tp = v->ob_type;
  324.     if (tp->tp_hash != NULL)
  325.         return (*tp->tp_hash)(v);
  326.     if (tp->tp_compare == NULL)
  327.         return (long) v; /* Use address as hash value */
  328.     /* If there's a cmp but no hash defined, the object can't be hashed */
  329.     err_setstr(TypeError, "unhashable type");
  330.     return -1;
  331. }
  332.  
  333. object *
  334. getattr(v, name)
  335.     object *v;
  336.     char *name;
  337. {
  338.     if (v->ob_type->tp_getattro != NULL) {
  339.         object *w, *res;
  340.         w = newstringobject(name);
  341.         if (w == NULL)
  342.             return NULL;
  343.         res = (*v->ob_type->tp_getattro)(v, w);
  344.         XDECREF(w);
  345.         return res;
  346.     }
  347.  
  348.     if (v->ob_type->tp_getattr == NULL) {
  349.         err_setstr(AttributeError, "attribute-less object");
  350.         return NULL;
  351.     }
  352.     else {
  353.         return (*v->ob_type->tp_getattr)(v, name);
  354.     }
  355. }
  356.  
  357. int
  358. hasattr(v, name)
  359.     object *v;
  360.     char *name;
  361. {
  362.     object *res = getattr(v, name);
  363.     if (res != NULL) {
  364.         DECREF(res);
  365.         return 1;
  366.     }
  367.     err_clear();
  368.     return 0;
  369. }
  370.  
  371. int
  372. setattr(v, name, w)
  373.     object *v;
  374.     char *name;
  375.     object *w;
  376. {
  377.     if (v->ob_type->tp_setattro != NULL) {
  378.         object *s;
  379.         int res;
  380.         s = newstringobject(name);
  381.         if (s == NULL)
  382.             return -1;
  383.         res = (*v->ob_type->tp_setattro)(v, s, w);
  384.         XDECREF(s);
  385.         return res;
  386.     }
  387.  
  388.     if (v->ob_type->tp_setattr == NULL) {
  389.         if (v->ob_type->tp_getattr == NULL)
  390.             err_setstr(TypeError,
  391.                    "attribute-less object (assign or del)");
  392.         else
  393.             err_setstr(TypeError,
  394.                    "object has read-only attributes");
  395.         return -1;
  396.     }
  397.     else {
  398.         return (*v->ob_type->tp_setattr)(v, name, w);
  399.     }
  400. }
  401.  
  402. /* Test a value used as condition, e.g., in a for or if statement.
  403.    Return -1 if an error occurred */
  404.  
  405. int
  406. testbool(v)
  407.     object *v;
  408. {
  409.     int res;
  410.     if (v == None)
  411.         res = 0;
  412.     else if (v->ob_type->tp_as_number != NULL)
  413.         res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
  414.     else if (v->ob_type->tp_as_mapping != NULL)
  415.         res = (*v->ob_type->tp_as_mapping->mp_length)(v);
  416.     else if (v->ob_type->tp_as_sequence != NULL)
  417.         res = (*v->ob_type->tp_as_sequence->sq_length)(v);
  418.     else
  419.         res = 1;
  420.     if (res > 0)
  421.         res = 1;
  422.     return res;
  423. }
  424.  
  425. /* Coerce two numeric types to the "larger" one.
  426.    Increment the reference count on each argument.
  427.    Return -1 and raise an exception if no coercion is possible
  428.    (and then no reference count is incremented).
  429. */
  430.  
  431. int
  432. coerce(pv, pw)
  433.     object **pv, **pw;
  434. {
  435.     register object *v = *pv;
  436.     register object *w = *pw;
  437.     int res;
  438.  
  439.     if (v->ob_type == w->ob_type && !is_instanceobject(v)) {
  440.         INCREF(v);
  441.         INCREF(w);
  442.         return 0;
  443.     }
  444.     if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
  445.         res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
  446.         if (res <= 0)
  447.             return res;
  448.     }
  449.     if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
  450.         res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
  451.         if (res <= 0)
  452.             return res;
  453.     }
  454.     err_setstr(TypeError, "number coercion failed");
  455.     return -1;
  456. }
  457.  
  458.  
  459. /* Test whether an object can be called */
  460.  
  461. int
  462. callable(x)
  463.     object *x;
  464. {
  465.     if (x == NULL)
  466.         return 0;
  467.     if (x->ob_type->tp_call != NULL ||
  468.         is_funcobject(x) ||
  469.         is_instancemethodobject(x) ||
  470.         is_methodobject(x) ||
  471.         is_classobject(x))
  472.         return 1;
  473.     if (is_instanceobject(x)) {
  474.         object *call = getattr(x, "__call__");
  475.         if (call == NULL) {
  476.             err_clear();
  477.             return 0;
  478.         }
  479.         /* Could test recursively but don't, for fear of endless
  480.            recursion if some joker sets self.__call__ = self */
  481.         DECREF(call);
  482.         return 1;
  483.     }
  484.     return 0;
  485. }
  486.  
  487.  
  488. /*
  489. NoObject is usable as a non-NULL undefined value, used by the macro None.
  490. There is (and should be!) no way to create other objects of this type,
  491. so there is exactly one (which is indestructible, by the way).
  492. */
  493.  
  494. /* ARGSUSED */
  495. static object *
  496. none_repr(op)
  497.     object *op;
  498. {
  499.     return newstringobject("None");
  500. }
  501.  
  502. static typeobject Notype = {
  503.     OB_HEAD_INIT(&Typetype)
  504.     0,
  505.     "None",
  506.     0,
  507.     0,
  508.     0,        /*tp_dealloc*/ /*never called*/
  509.     0,        /*tp_print*/
  510.     0,        /*tp_getattr*/
  511.     0,        /*tp_setattr*/
  512.     0,        /*tp_compare*/
  513.     (reprfunc)none_repr, /*tp_repr*/
  514.     0,        /*tp_as_number*/
  515.     0,        /*tp_as_sequence*/
  516.     0,        /*tp_as_mapping*/
  517.     0,        /*tp_hash */
  518. };
  519.  
  520. object NoObject = {
  521.     OB_HEAD_INIT(&Notype)
  522. };
  523.  
  524.  
  525. #ifdef Py_TRACE_REFS
  526.  
  527. static object refchain = {&refchain, &refchain};
  528.  
  529. void
  530. NEWREF(op)
  531.     object *op;
  532. {
  533.     ref_total++;
  534.     op->ob_refcnt = 1;
  535.     op->_ob_next = refchain._ob_next;
  536.     op->_ob_prev = &refchain;
  537.     refchain._ob_next->_ob_prev = op;
  538.     refchain._ob_next = op;
  539. #ifdef COUNT_ALLOCS
  540.     inc_count(op->ob_type);
  541. #endif
  542. }
  543.  
  544. void
  545. UNREF(op)
  546.     register object *op;
  547. {
  548.     register object *p;
  549.     if (op->ob_refcnt < 0)
  550.         fatal("UNREF negative refcnt");
  551.     if (op == &refchain ||
  552.         op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
  553.         fatal("UNREF invalid object");
  554. #ifdef SLOW_UNREF_CHECK
  555.     for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
  556.         if (p == op)
  557.             break;
  558.     }
  559.     if (p == &refchain) /* Not found */
  560.         fatal("UNREF unknown object");
  561. #endif
  562.     op->_ob_next->_ob_prev = op->_ob_prev;
  563.     op->_ob_prev->_ob_next = op->_ob_next;
  564.     op->_ob_next = op->_ob_prev = NULL;
  565. #ifdef COUNT_ALLOCS
  566.     op->ob_type->tp_free++;
  567. #endif
  568. }
  569.  
  570. void
  571. DELREF(op)
  572.     object *op;
  573. {
  574.     destructor dealloc = op->ob_type->tp_dealloc;
  575.     UNREF(op);
  576.     op->ob_type = NULL;
  577.     (*dealloc)(op);
  578. }
  579.  
  580. void
  581. _Py_PrintReferences(fp)
  582.     FILE *fp;
  583. {
  584.     object *op;
  585.     fprintf(fp, "Remaining objects (except strings referenced once):\n");
  586.     for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
  587.         if (op->ob_refcnt == 1 && is_stringobject(op))
  588.             continue; /* Will be printed elsewhere */
  589.         fprintf(fp, "[%d] ", op->ob_refcnt);
  590.         if (printobject(op, fp, 0) != 0)
  591.             err_clear();
  592.         putc('\n', fp);
  593.     }
  594. }
  595.  
  596. PyObject *
  597. _Py_GetObjects(self, args)
  598.     PyObject *self;
  599.     PyObject *args;
  600. {
  601.     int i, n;
  602.     PyObject *t = NULL;
  603.     PyObject *res, *op;
  604.  
  605.     if (!PyArg_ParseTuple(args, "i|O", &n, &t))
  606.         return NULL;
  607.     op = refchain._ob_next;
  608.     res = PyList_New(0);
  609.     if (res == NULL)
  610.         return NULL;
  611.     for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
  612.         while (op == self || op == args || op == res || op == t ||
  613.                t != NULL && op->ob_type != (PyTypeObject *) t) {
  614.             op = op->_ob_next;
  615.             if (op == &refchain)
  616.                 return res;
  617.         }
  618.         if (PyList_Append(res, op) < 0) {
  619.             Py_DECREF(res);
  620.             return NULL;
  621.         }
  622.         op = op->_ob_next;
  623.     }
  624.     return res;
  625. }
  626.  
  627. #endif
  628.  
  629.  
  630. /* Hack to force loading of cobject.o */
  631. static PyTypeObject *cobject_hack = &PyCObject_Type;
  632.  
  633.  
  634. /* Hack to force loading of abstract.o */
  635. static int (*abstract_hack) FPROTO((PyObject *)) = &PyObject_Length;
  636.